<template>
  <div class="outbound-order-page">
    <!-- 数据筛选区域 -->
    <div class="filter-section">
      <el-row>
        <el-col :span="6">
          <el-form-item label="出库单号">
            <el-input v-model="page.outboundnumber" placeholder="请输入/扫描单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据类型" style="margin-left: 12px;">
            <el-select v-model="page.outbound" placeholder="请选择">
              <el-option label="领料出库" :value="101"></el-option>
              <el-option label="产品出库" :value="102"></el-option>
              <el-option label="销售出库" :value="103"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出库单状态" style="margin-left: 12px;">
            <el-select v-model="page.outAuditstatus" placeholder="请选择">
              <el-option label="待处理" :value="101"></el-option>
              <el-option label="处理中" :value="102"></el-option>
              <el-option label="已通过" :value="103"></el-option>
              <el-option label="已拒绝" :value="104"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="getoutprolist();" style="margin-left: 12px;">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <!-- <el-button type="text" class="advanced-search">高级搜索</el-button> -->
        </el-col>
      </el-row>
    </div>

    <!-- 数据列表区域 -->
    <div class="data-list-section">
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <!-- <el-button @click="handleEdit">编辑</el-button> -->
          <el-button type="danger" @click="handleDeleteAll(selectedIds)">删除</el-button>
          <el-button type="success"  @click="handleRefresh">刷新</el-button>
          <!-- <el-button @click="handleExport">导出</el-button> -->
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: auto" @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="outboundnumber" label="订单号"></el-table-column>
        <el-table-column prop="productName" label="产品名称"  width="150px"></el-table-column>
        <el-table-column prop="productId" label="产品编号"  width="150px"></el-table-column>
        <el-table-column prop="batch" label="批次"></el-table-column>
        <el-table-column prop="specification" label="规格" width="150px"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>
        <el-table-column prop="binlocation" label="库位" width="150px"></el-table-column>
        <el-table-column prop="outbound" label="出库类型 " width="150px">
          <template v-slot="scope">
            <p v-if="scope.row.outbound==101">领料出库</p>
            <p v-if="scope.row.outbound==102">产品出库</p>
            <p v-if="scope.row.outbound==103">销售出库</p>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="customer" label="客户"></el-table-column> -->
        <el-table-column prop="outCreator" label="制单人"></el-table-column>
        <el-table-column prop="outAuditstatus" label="状态">
          <template v-slot="scope">
            <p v-if="scope.row.outAuditstatus==101">待处理</p>
            <p v-if="scope.row.outAuditstatus==102">处理中</p>
            <p v-if="scope.row.outAuditstatus==103">已通过</p>
            <p v-if="scope.row.outAuditstatus==104">已拒绝</p>
          </template>
        </el-table-column>
        <el-table-column prop="auditor" label="审核人"></el-table-column>
        <el-table-column prop="auditTime" label="审核时间"  width="150px"></el-table-column>
        <el-table-column label="操作" width="190px">
          <template #default="scope">
             <el-button link type="success" @click="handleView(scope.row)">查看</el-button>
           <el-button type="text" @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <!-- <el-button type="text" @click="handleAudit(scope.row)">审核</el-button>
            <el-button type="text" @click="handlePrint(scope.row)">打印</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="page.pageindex"
      v-model:page-size="page.pageSize"
      :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pages.totalcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
  </div>
  </div>
<!-- 出库详情 -->
<el-dialog title="出库单详情" v-model="dialogFormVisible" width="60%">
     <!-- 上半部分信息 - 使用grid布局实现两列显示 -->
     <div class="detail-info-grid">
      <!-- 使用grid布局，每行两列 -->
      <div class="grid-row">
        <div class="grid-item">
          <span class="label">出库单号：</span>
          <span class="value">{{ form.outboundnumber }}</span>
        </div>
        <div class="grid-item">
          <span class="label">出库单类型：</span>
          <span class="value">
            <template v-if="form.outbound==101">领料出库</template>
            <template v-if="form.outbound==102">产品出库</template>
            <template v-if="form.outbound==103">销售出库</template>
          </span>
        </div>
      </div>
      
      <div class="grid-row">
        <div class="grid-item">
          <span class="label">出库状态：</span>
          <span class="value">
            <template v-if="form.outAuditstatus==101">待处理</template>
            <template v-if="form.outAuditstatus==102">处理中</template>
            <template v-if="form.outAuditstatus==103">已通过</template>
            <template v-if="form.outAuditstatus==104">已拒绝</template>
          </span>
        </div>
        <div class="grid-item">
          <span class="label">供应商编号：</span>
          <span class="value">{{ form.supplierID }}</span>
        </div>
      </div>
      
      <div class="grid-row">
        <div class="grid-item">
          <span class="label">供应商名称：</span>
          <span class="value">{{ form.supplierName }}</span>
        </div>
        <div class="grid-item">
          <span class="label">联系人：</span>
          <span class="value">{{ form.supplierPeople }}</span>
        </div>
      </div>
      
      <div class="grid-row">
        <div class="grid-item">
          <span class="label">电话：</span>
          <span class="value">{{ form.supplierPhone }}</span>
        </div>
        <div class="grid-item">
          <span class="label">制单人：</span>
          <span class="value">{{ form.creator }}</span>
        </div>
      </div>
      
      <div class="grid-row">
        <div class="grid-item">
          <span class="label">制单日期：</span>
          <span class="value">{{ form.outCreationTime ? form.outCreationTime.substring(0, 10) : "" }}</span>
        </div>
        <div class="grid-item">
          <span class="label">备注：</span>
          <span class="value">{{ form.rember || '无' }}</span>
        </div>
      </div>
      
      <!-- 审核原因单独一行 -->
      <div class="grid-row-full">
        <div class="grid-item">
          <span class="label">审核原因：</span>
          <span class="value">{{ form.shenRember || '同意' }}</span>
        </div>
      </div>
    </div>

    <!-- 下半部分表格 -->
    <el-table :data="tableDetails" style="margin-top: 20px;width:auto" border>
      <el-table-column prop="productId" label="产品编码" />
      <el-table-column prop="productName" label="产品名称" />
      <el-table-column prop="specification" label="规格" />
      <el-table-column prop="batch" label="批次" />
      <el-table-column prop="price" label="单价" align="right">
        <template #default="{row}">
          {{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="入库数" align="center" />
      <el-table-column prop="totalprice" label="总价" align="right">
        <template #default="{row}">
          {{ row.totalprice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="binlocation" label="库位" />
    </el-table>

    <div style="text-align: right; margin-top: 20px">
      <el-button @click="dialogFormVisible = false">关闭</el-button>
    </div>
</el-dialog>
</template>

<script setup>
import { ElRow, ElCol, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElTable, ElTableColumn } from 'element-plus';
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCounterStore } from "@/stores/counter";
import {useRoute,useRouter} from 'vue-router'
import { KongaUrl } from '@/axios/axiosHelp';

// 模拟数据
const mockData = ref([]);
const page=reactive({
  outboundnumber:'',
  outbound:'',
  outAuditstatus:'',
  pageindex:1,
  pageSize:15
})
const pages=reactive({
totalpage:0,
totalcount:0
})
onMounted(()=>{
  getoutprolist();
})
let router=useRouter();

const getoutprolist=()=>{
KongaUrl({
  url:'/activity/api/OutManage/GetProductsByConditions',
  method:'get',
  params:{
    outboundnumber:page.outboundnumber,
    outbound:page.outbound,
    outAuditstatus:page.outAuditstatus,
    pageindex:page.pageindex,
    pageSize:page.pageSize,

  }
})
.then(res=>{
 
    console.log(res)
    tableData.value=res.data.result.list;
    pages.totalcount=res.data.result.totalcount
    pages.totalpage=res.data.result.totalpage
    // 这里添加更新tableData
    // tableData.value = res.data;
})
}
// 弹窗相关变量
const dialogFormVisible  = ref(false);
// 表格数据
const tableData = ref(mockData.value);
// 用于展示详情表格的数据，初始化为空数组
const tableDetails = ref([]); 

// 重置筛选条件方法
const resetFilter = () => {
  page.outboundNumber = '';
  page.outbound = '';
  page.outAuditstatus = '';
  getoutprolist();
};

// 新增按钮点击方法
const handleAdd = () => {
router.push("/AddOutAount")
  // 可在此添加打开新增表单等逻辑
};

// 编辑按钮点击方法
const handleEdit = (id) => {
  console.log('传的数据',id)
  router.push({
    name:'UpdateOutAount',
    query:{
      id:id
    }
    
  })
  console.log('编辑操作', id);
  // 可在此添加打开编辑表单等逻辑
};

// 删除按钮点击方法
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除吗?',
      '警告',
      {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
      }
  )
  .then(()=>{
    KongaUrl({
    url:'/activity/api/OutManage/DeleteOutManage',
    method:'post',
    params:{
      id:row.id
    }
  })
  .then(res=>{
    if(res.status==200){
      ElMessage.success("删除成功")
      getoutprolist();
    }
  })
  })
  .catch(() => {
          ElMessage({
              type: 'info',
              message: '取消',
          })
      })

  
  console.log('删除操作', row);
  // 可在此添加实际删除逻辑，如确认提示、后端请求等
};

const selectedIds = ref([])

// 选择项变化
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
  console.log('选中的数据', selectedIds.value)
}

// 批量删除操作
const handleDeleteAll = (ids) => {
  console.log('选中批量的数据', ids.length)
  console.log('选中的数据', ids)
  
  if(ids.length === 0){
    ElMessage.error("请选择数据")
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${ids.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    try {
      // 修正后的请求方式
      const response = await KongaUrl({
        url: '/activity/api/OutManage/DeleteOutManageALL',
        method: 'post',
        data:ids
      })
      
      if(response.status === 200) {
        ElMessage.success('删除成功')
        // 刷新数据
        getoutprolist();
      } 
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 刷新按钮点击方法
const handleRefresh = () => {
  getoutprolist();
};

// 导出按钮点击方法
const handleExport = () => {
  console.log('导出操作');
  // 可在此添加实际导出逻辑，如调用后端接口生成文件等
};


const form = reactive({
"pid": '',
"outboundnumber": Math.floor(Math.random() * (999 - 100 + 1)) + 100,
"associatedNum": "",
"batch": "",
"specifications": "",
"quantity": 0,
"totalprice": 0,
"location": "",
"outbound": 101,
"supplier": "",
"supplierID": "",
"supplierName": "",
"supplierPeople": "",
"supplierPhone": "",
"outCreator": '',
"reviewer": "",
"outAuditTime": new Date().toISOString(),
"outAuditstatus": 101,
"outCreationTime": new Date().toISOString(),
"rember": "",
"shenRember": ""
});


// 添加解析花括号数据的方法
const parseBracketData = (dataString) => {
  if (!dataString) return [];
  // 移除花括号并按逗号分隔
  return dataString.replace(/\{|\}/g, '').split(',').map(item => item.trim());
};

// 查看按钮点击方法
const handleView = (row) => {
  console.log('查看行数据:', row);
  
  // 填充表单数据
  Object.assign(form, {
    pid: row.pId,
    outboundnumber: row.outboundnumber,
    associatedNum: row.associatedNum,
    batch: row.batch,
    specifications: row.specifications,
    quantity: row.quantity,
    totalprice: row.totalprice,
    location: row.location,
    outbound: row.outbound,
    supplier: row.supplier,
    supplierID: row.supplierID,
    supplierName: row.supplierName,
    supplierPeople: row.supplierPeople,
    supplierPhone: row.supplierPhone,
    outCreator: row.outCreator,
    reviewer: row.outReviewer,
    outAuditTime: row.outAuditTime,
    outAuditstatus: row.outAuditstatus,
    outCreationTime: row.outCreationTime,
    rember: row.rember,
    shenRember: row.shenRember
  });

  // 解析产品数据
  const productIds = parseBracketData(row.productId);
  const productNames = parseBracketData(row.productName);
  const specifications = parseBracketData(row.specification);
  const batches = parseBracketData(row.batch);
  const prices = parseBracketData(row.price);
  const quantities = parseBracketData(row.quantity);
  const totalprices = parseBracketData(row.totalprice);
  const binlocations = parseBracketData(row.binlocation);

  // 构建详情表格数据
  tableDetails.value = productIds.map((id, index) => ({
    productId: id,
    productName: productNames[index] || '',
    specification: specifications[index] || '',
    batch: batches[index] || '',
    price: parseFloat(prices[index]) || 0,
    quantity: parseFloat(quantities[index]) || 0,
    totalprice: parseFloat(totalprices[index]) || 0,
    binlocation: binlocations[index] || ''
  }));

  dialogFormVisible.value = true;
};
// 审核按钮点击方法
const handleAudit = (row) => {
  console.log('审核操作', row);
  // 可在此添加实际审核逻辑，如调用后端接口等
};

// 打印按钮点击方法
const handlePrint = (row) => {
  console.log('打印操作', row);
  // 可在此添加实际打印逻辑，如调用打印插件等
};

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  page.pageSize=val;
  getoutprolist();

}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  page.pageindex=val;
  getoutprolist();
}
</script>

<style scoped>
/* 新增的grid布局样式 */
.detail-info-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.grid-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.grid-row-full {
  grid-column: 1 / -1;
}

.grid-item {
  display: flex;
  min-width: 0;
}

.label {
  font-weight: bold;
  min-width: 80px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
  word-break: break-word;
}
.outbound-order-page {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.data-list-section {
  border: 1px solid #e9e9e9;
  padding: 10px;
}

.advanced-search {
  margin-left: 10px;
  color: #409eff;
  text-decoration: underline;
}
</style>